<template>
    <div>
        <el-breadcrumb separator="/" style="padding-left:10px;padding-bottom:10px;font-size:12px;">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>系统管理</el-breadcrumb-item>
            <el-breadcrumb-item>员工管理</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 用户列表卡片区 -->
        <el-card class="box-card">
            <el-form :inline="true" ref="form" :model="queryMap" label-width="70px" size="small">
                <el-form-item label="部门">
                    <el-select
                            clearable
                            @change="searchEmp"
                            @clear="searchEmp"
                            v-model="queryMap.deptId"
                            placeholder="请选择所属部门"
                    >
                        <el-option
                                v-for="department in departments"
                                :label="department.deptName"
                                :key="department.deptId"
                                :value="department.deptId"
                        >
                            <span style="float: left">{{ department.deptName }}</span>
                            <span style="float: right; color: #8492a6; font-size: 13px">
                <el-tag size="small" effect="plain" type="success">
                  {{ department.total }}人
                </el-tag>
              </span>
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="员工名称">
                    <el-input
                            @keyup.enter.native="searchEmp"
                            @clear="searchEmp"
                            clearable
                            v-model="queryMap.empname"
                            placeholder="请输入员工名查询"
                    ></el-input>
                </el-form-item>

                <el-form-item label="电话">
                    <el-input
                            @keyup.enter.native="searchEmp"
                            clearable
                            @clear="searchEmp"
                            v-model="queryMap.moblie"
                            placeholder="请输入邮箱查询"
                    ></el-input>
                </el-form-item>

                <el-form-item label="性别">
                    <el-radio v-model="queryMap.sex" label="1">男</el-radio>
                    <el-radio v-model="queryMap.sex" label="0">女</el-radio>
                    <el-radio v-model="queryMap.sex" label>全部</el-radio>
                </el-form-item>

                <el-form-item label="状态">
                  <el-select
                    clearable
                    v-model="queryMap.empstatus"
                    @clear="searchEmp"
                    placeholder="请选择员工状态"
                  >
                    <el-option label="全部" value=""></el-option>
                    <el-option label="在职" value="1"></el-option>
                    <el-option label="离职" value="2"></el-option>
                    <el-option label="开除" value="3"></el-option>
                    <el-option label="其他" value="4"></el-option>
                  </el-select>
                </el-form-item>

                <el-form-item style="margin-left:50px;">
                    <el-button  @click="reset" icon="el-icon-refresh">重置</el-button>
                    <el-button type="primary" @click="searchEmp" icon="el-icon-search">查询</el-button>
                    <el-button
                            type="success"
                            icon="el-icon-plus"
                            @click="addDialogVisible=true"
                            v-hasPermission="'emp:add'"
                    >添加</el-button>
                    <el-button @click="downExcel" v-hasPermission="'user:export'"  icon="el-icon-download">导出</el-button>
                </el-form-item>
            </el-form>

            <!-- 表格区域 -->
            <el-table v-loading="loading" size="small" :data="empList" border style="width: 100%;" height="420">
                <!-- <el-table-column type="selection" width="40"></el-table-column> -->
                <el-table-column label="#" prop="empid" width="50"></el-table-column>
                <el-table-column prop="empname" label="用户名" width="80"></el-table-column>
                <el-table-column prop="sex" label="性别" width="50"></el-table-column>
                <el-table-column prop="departmentName" label="所属部门" width="110" sortable></el-table-column>
                <el-table-column prop="birthdate" label="生日" width="130" sortable></el-table-column>
                <el-table-column prop="hiredate" label="入职日期" width="130"></el-table-column>
                <el-table-column prop="moblie" label="电话" width="130"></el-table-column>
              <el-table-column prop="empstatus"  label="员工状态" width="80">
                <template slot-scope="scope">
                  <span>{{showEmpStatusName(scope.row)}}</span>
                </template>
              </el-table-column>
                <el-table-column label="操作" >
                    <template slot-scope="scope">
                        <el-button   v-hasPermission="'emp:edit'" size="small" type="primary" icon="el-icon-edit-outline" @click="edit(scope.row.empid)"></el-button>
                        <el-button v-hasPermission="'emp:delete'" type="danger" size="small" icon="el-icon-delete" @click="del(scope.row.empid)"></el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <el-pagination
                    style="margin-top:10px;"
                    background
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="queryMap.pageNo"
                    :page-sizes="[6, 10, 20, 30]"
                    :page-size="queryMap.pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
            ></el-pagination>

            <!-- 添加对话框 -->
            <el-dialog title="添加员工" @close="closeDialog" :visible.sync="addDialogVisible" width="50%;">
                <!-- 表单 -->
                <span>
          <el-form
                  :model="addForm"
                  :label-position="labelPosition"
                  :rules="addFormRules"
                  ref="addFormRef"
                  label-width="80px"
          >
            <el-row>
              <el-col :span="10">
                <div class="grid-content bg-purple">
                  <el-form-item label="员工姓名" prop="empname">
                    <el-input v-model="addForm.empname"></el-input>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="grid-content bg-purple-light">
                  <el-form-item label="部门" prop="departmentId">
                    <el-select v-model="addForm.deptId" placeholder="请选择所属部门">
                      <el-option
                              v-for="department in departments"
                              :key="department.deptId"
                              :label="department.deptName"
                              :value="department.deptId"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="10">
                <div class="grid-content bg-purple">
                  <el-form-item label="年龄" prop="age">
                    <el-input v-model="addForm.age"></el-input>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="grid-content bg-purple-light">
                  <el-form-item label="性别" prop="sex">
                    <el-radio-group v-model="addForm.sex">
                      <el-radio label="男" :value="0">男</el-radio>
                      <el-radio label="女" :value="1">女</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>

             <el-row>
              <el-col :span="10">
                <div class="grid-content bg-purple">
                  <el-form-item label="出生日期" prop="birthdate">
                      <el-col :span="11">
                        <el-date-picker
                            type="date"
                            value-format="yyyy年MM月dd日"
                            placeholder="选择出生日期"
                            v-model="addForm.birthdate"
                            style="width: 185px;"
                        ></el-date-picker>
                    </el-col>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="grid-content bg-purple-light">
                  <el-form-item label="入职日期" prop="hiredate">
                      <el-col :span="11">
                        <el-date-picker
                            type="date"
                            value-format="yyyy年MM月dd日"
                            placeholder="选择入职日期"
                            v-model="addForm.hiredate"
                            style="width: 185px;"
                        ></el-date-picker>
                    </el-col>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>

             <el-row>
              <el-col :span="10">
                <div class="grid-content bg-purple">
                  <el-form-item label="学历" prop="educationbackground">
                    <el-select v-model="addForm.educationbackground" placeholder="请选择学历">
                      <el-option label="大专" :value="1"></el-option>
                      <el-option label="大学本科" :value="2"></el-option>
                      <el-option label="研究生硕士" :value="3"></el-option>
                      <el-option label="研究生博士" :value="4"></el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="grid-content bg-purple-light">
                  <el-form-item label="专业" prop="major">
                    <el-input v-model="addForm.major"></el-input>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>
            <el-form-item label="联系电话" prop="moblie">
              <el-input v-model="addForm.moblie"></el-input>
            </el-form-item>
            <el-form-item label="家庭住址" prop="password">
              <el-input v-model="addForm.password"></el-input>
            </el-form-item>
            <el-form-item label="现居住地址" prop="email">
              <el-input v-model="addForm.email"></el-input>
            </el-form-item>
            <el-form-item label="毕业学校" prop="phoneNumber">
              <el-input v-model="addForm.phoneNumber"></el-input>
            </el-form-item>
            <el-form-item label="简历信息" prop="resumeinformation">
              <el-input type="textarea" v-model="addForm.resumeinformation"></el-input>
            </el-form-item>
                  <el-form-item label="员工状态" prop="empstatus">
                    <el-select v-model="addForm.empstatus" placeholder="请选择专业">
                      <el-option label="在职" :value="1"></el-option>
                      <el-option label="离职" :value="2"></el-option>
                      <el-option label="开除" :value="3"></el-option>
                      <el-option label="其他" :value="4"></el-option>
                    </el-select>
                  </el-form-item>
            <el-form-item label="备注" prop="remarks">
              <el-input type="textarea" v-model="addForm.remarks"></el-input>
            </el-form-item>
          </el-form>
        </span>

                <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button
                  type="primary"
                  @click="addEmp"
                  :loading="btnLoading"
                  :disabled="btnDisabled"
          >确 定</el-button>
        </span>
            </el-dialog>
            <!-- 修改对话框 -->
            <el-dialog title="修改员工" :visible.sync="editDialogVisible" width="50%" @close="editClose">
        <span>
          <el-form
                  :model="editForm"
                  :label-position="labelPosition"
                  :rules="addFormRules"
                  ref="editFormRef"
                  label-width="80px"
          >
          <el-row>
              <el-col :span="10">
                <div class="grid-content bg-purple">
                  <el-form-item label="员工姓名" prop="empname">
                    <el-input v-model="editForm.empname"></el-input>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="grid-content bg-purple-light">
                  <el-form-item label="部门" prop="departmentId">
                    <el-select v-model="editForm.deptId" placeholder="请选择所属部门">
                      <el-option
                          v-for="department in departments"
                          :key="department.deptId"
                          :label="department.deptName"
                          :value="department.deptId"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="10">
                <div class="grid-content bg-purple">
                  <el-form-item label="年龄" prop="age">
                    <el-input v-model="editForm.age"></el-input>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="grid-content bg-purple-light">
                  <el-form-item label="性别" prop="sex">
                    <el-radio-group v-model="editForm.sex">
                      <el-radio label="男" :value="0">男</el-radio>
                      <el-radio label="女" :value="1">女</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>

             <el-row>
              <el-col :span="10">
                <div class="grid-content bg-purple">
                  <el-form-item label="出生日期" prop="birthdate">
                      <el-col :span="11">
                        <el-date-picker
                            type="date"
                            value-format="yyyy年MM月dd日"
                            placeholder="选择出生日期"
                            v-model="editForm.birthdate"
                            style="width: 185px;"
                        ></el-date-picker>
                    </el-col>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="grid-content bg-purple-light">
                  <el-form-item label="入职日期" prop="hiredate">
                      <el-col :span="11">
                        <el-date-picker
                            type="date"
                            value-format="yyyy年MM月dd日"
                            placeholder="选择入职日期"
                            v-model="editForm.hiredate"
                            style="width: 185px;"
                        ></el-date-picker>
                    </el-col>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>

             <el-row>
              <el-col :span="10">
                <div class="grid-content bg-purple">
                  <el-form-item label="学历" prop="educationbackground">
                    <el-select v-model="editForm.educationbackground" placeholder="请选择学历">
                      <el-option label="大专" :value="1"></el-option>
                      <el-option label="大学本科" :value="2"></el-option>
                      <el-option label="研究生硕士" :value="3"></el-option>
                      <el-option label="研究生博士" :value="4"></el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="grid-content bg-purple-light">
                  <el-form-item label="专业" prop="major">
                    <el-input v-model="editForm.major"></el-input>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>
            <el-form-item label="联系电话" prop="moblie">
              <el-input v-model="editForm.moblie"></el-input>
            </el-form-item>
            <el-form-item label="家庭住址" prop="password">
              <el-input v-model="editForm.password"></el-input>
            </el-form-item>
            <el-form-item label="现居住地址" prop="email">
              <el-input v-model="editForm.email"></el-input>
            </el-form-item>
            <el-form-item label="毕业学校" prop="phoneNumber">
              <el-input v-model="editForm.phoneNumber"></el-input>
            </el-form-item>
            <el-form-item label="简历信息" prop="resumeinformation">
              <el-input type="textarea" v-model="editForm.resumeinformation"></el-input>
            </el-form-item>
                  <el-form-item label="员工状态" prop="empstatus">
                    <el-select v-model="editForm.empstatus" placeholder="请选择专业">
                      <el-option label="在职" :value="1"></el-option>
                      <el-option label="离职" :value="2"></el-option>
                      <el-option label="开除" :value="3"></el-option>
                      <el-option label="其他" :value="4"></el-option>
                    </el-select>
                  </el-form-item>
            <el-form-item label="备注" prop="remarks">
              <el-input type="textarea" v-model="editForm.remarks"></el-input>
            </el-form-item>
          </el-form>
        </span>

                <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button
                  type="primary"
                  @click="updateEmp"
                  :loading="btnLoading"
                  :disabled="btnDisabled"
          >确 定</el-button>
        </span>
            </el-dialog>
        </el-card>
    </div>
</template>
<script>
    import axios from "axios";
    export default {
        data() {
            const checkIdCard = (rule, value, callback) => {
              const mailReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
                if (!value) {
                    return callback(new Error("身份证不能为空"));
                }
                setTimeout(() => {
                    if (mailReg.test(value)) {
                        callback();
                    } else {
                        callback(new Error("请输入正确的身份证格式"));
                    }
                }, 100);
            };
            const checkPhone = (rule, value, callback) => {
                const phoneReg = /^1[34578]\d{9}$$/;
                if (!value) {
                    return callback(new Error("电话号码不能为空"));
                }
                setTimeout(() => {
                    if (!Number.isInteger(+value)) {
                        callback(new Error("请输入数字值"));
                    } else {
                        if (phoneReg.test(value)) {
                            callback();
                        } else {
                            callback(new Error("电话号码格式不正确"));
                        }
                    }
                }, 100);
            };
            return {
                btnLoading: false,
                btnDisabled: false,
                departments: [],
                loading: true,
                total: 0,
                addDialogVisible: false, //添加对话框,
                editDialogVisible: false, //修改对话框
                assignDialogVisible: false, //分配角色对话框
                labelPosition: "right", //lable对齐方式
                //查询对象
                queryMap: {
                    pageNum: 1,
                    pageSize: 6,
                    empname: "",
                    sex: "",
                  deptId:"",
                    moblie:"",
                    empstatus: ""
                },
                empList: [],

                addForm: {
                  empname: "",
                  sex: "",
                  age: "",
                  birthdate: "",
                  identitycard: "",
                  moblie: "",
                  nativeplace: "",
                  currentresidence: "",
                  deptId: "",
                  hiredate: "",
                  educationbackground: "",
                  graduationschool: "",
                  major: "",
                  resumeinformation: "",
                  empstatus: "",
                  remarks: ""
                }, //添加表单
                editForm: {}, //更新表单
                addFormRules: {
                  empname: [
                        { required: true, message: "请输入员工名", trigger: "blur" },
                        { min: 2, max: 10, message: "长度在 2 到 10 个字符", trigger: "blur" }
                    ],
                  deptId: [
                        { required: true, message: "请选择部门", trigger: "blur" }
                    ],
                  empstatus: [
                    { required: true, message: "请选状态", trigger: "blur" }
                  ],
                    sex: [{ required: true, message: "请选择性别", trigger: "blur" }],
                    birthdate: [{ required: true, message: "请填写出生日期", trigger: "blur" }],
                  identitycard: [{ required: true, validator: checkIdCard, trigger: "blur" }],
                  moblie: [
                        {
                            required: true,
                            message: "请输入联系方式",
                            validator: checkPhone,
                            trigger: "blur"
                        }
                    ],
                    nickname: [
                        { required: true, message: "请输入昵称", trigger: "blur" },
                        { min: 5, max: 10, message: "长度在 5 到 10 个字符", trigger: "blur" }
                    ]
                }, //添加表单验证规则
            };
        },
        methods: {

            /**
             * 重置
             */
            reset(){
                this.queryMap= {
                  pageNum: 1,
                  pageSize: 6,
                  empname: "",
                  sex: "",
                  deptId:"",
                  moblie:"",
                  empstatus: ""
                };
            },
            /**
             * 加载用户表格
             */
            downExcel() {
                const $this = this;
                const res = axios
                    .request({
                        url: "http://localhost:8989/emp/excel",
                        method: "post",
                        responseType: "blob",
                        headers:{'Authorization':LocalStorage.get(LOCAL_KEY_XINGUAN_ACCESS_TOKEN)},	//设置请求头
                    })
                    .then(res => {
                        if (res.headers["content-type"] === "application/json") {
                            return $this.$message.error(
                                "Subject does not have permission [emp:export]"
                            );
                        }
                        const data = res.data;
                        let url = window.URL.createObjectURL(data); // 将二进制文件转化为可访问的url
                        const a = document.createElement("a");
                        document.body.appendChild(a);
                        a.href = url;
                        a.download = "员工列表.xls";
                        a.click();
                        window.URL.revokeObjectURL(url);
                    });
            },
            /**
             * 加载员工列表
             */
            async getEmpList() {
                const { data: res } = await this.$http.get("emp/findList", {
                    params: this.queryMap
                });
                if(!res.success){
                    return this.$message.error("获取员工列表失败:"+res.data.errorMsg);
                }
                this.total = res.data.total;
                this.empList = res.data.rows;
            },

            /**
             * 删除员工
             */
            async del(id) {
                const res = await this.$confirm(
                    "此操作将永久删除该员工, 是否继续?",
                    "提示",
                    {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning"
                    }
                ).catch(() => {
                    this.$message({
                        type: "info",
                        message: "已取消删除"
                    });
                });
                if (res === "confirm") {
                    const { data: res } = await this.$http.delete("emp/delete/" + id);
                    console.log(res);
                    if(res.success){
                        this.$notify.success({
                            title:'操作成功',
                            message:'员工删除成功',
                        });
                        await this.getEmpList();
                        await this.getDepartmets();
                    }else {
                        this.$message.error(res.data.errorMsg);
                    }
                }
            },
            /**
             * 添加员工
             */
            async addEmp() {
                this.$refs.addFormRef.validate(async valid => {
                    if (!valid) {
                        return;
                    } else {
                        this.btnLoading = true;
                        this.btnDisabled = true;
                        const { data: res } = await this.$http.post("emp/add", this.addForm);
                        if(res.success){
                            this.$notify.success({
                                title:'操作成功',
                                message:'员工添加成功',
                            });
                            this.addForm = {};
                            await this.getEmpList();
                            await this.getDepartmets();
                        } else {
                            return this.$message.error("员工添加失败:" + res.data.errorMsg);
                        }
                        this.addDialogVisible = false;
                        this.btnLoading = false;
                        this.btnDisabled = false;
                    }
                });
            },
            /**
             * 更新员工
             */
            async updateEmp() {
                this.$refs.editFormRef.validate(async valid => {
                    if (!valid) {
                        return;
                    } else {
                        this.btnLoading = true;
                        this.btnDisabled = true;
                        const { data: res } = await this.$http.put(
                            "emp/update/" + this.editForm.empid,
                            this.editForm
                        );
                        if(res.success){
                            this.$notify({
                                title: "操作成功",
                                message: "员工基本信息已更新",
                                type: "success"
                            });
                            this.editForm = {};
                            await this.getEmpList();
                            await this.getDepartmets();
                        } else {
                            this.$message.error("员工信息更新失败:" + res.data.errorMsg);
                        }
                        this.editDialogVisible = false;
                        this.btnLoading = false;
                        this.btnDisabled = false;
                    }
                });
            },
            /**
             * 搜索员工
             */
            searchEmp() {
                this.queryMap.pageNum = 1;
                this.getEmpList();
            },
            /**
             * 修改员工信息
             */
            async edit(id) {
                const { data: res } = await this.$http.get("emp/edit/" + id);
                if(res.success){
                    this.editForm = res.data;
                    this.editDialogVisible = true;
                } else {
                    return this.$message.error("员工信息编辑失败:" + res.data.errorMsg);
                }
            },
            /**
             *  改变页码
             */
            handleSizeChange(newSize) {
                this.queryMap.pageSize = newSize;
                this.getEmpList();
            },
            /**
             * 翻页
             */
            handleCurrentChange(current) {
                this.queryMap.pageNum = current;
                this.getEmpList();
            },

            /**
             * 关闭添加弹出框
             */
            closeDialog() {
                this.$refs.addFormRef.clearValidate();
                this.addForm.birth = "";
                this.addForm = {};
            },
            /**
             * 关闭编辑弹出框
             */
            editClose() {
                this.$refs.editFormRef.clearValidate();
                this.editForm = {};
            },

          /**
           * 显示专业名称
           */
          showEmpStatusName(row, column) {
            let statusName = '';
            if(row.empstatus===1){
              statusName ='在职';
            }else if(row.empstatus===2){
              statusName ='离职';
            }else if(row.empstatus===3){
              statusName ='开除';
            }else if(row.empstatus===4){
              statusName ='其他';
            }
            return statusName;
          },

            /**
             * 加载所有部门
             */
            async getDepartmets() {
                const { data: res } = await this.$http.get("system/department/findAll");
                if(!res.success){
                    return this.$message.error("获取部门列表失败:"+res.data.errorMsg);
                }
                console.log("dep:",res.data);
                this.departments = res.data;
            },
        },
        created() {
            this.getEmpList();
            this.getDepartmets();
            setTimeout(() => {
                this.loading = false;
            }, 500);
        }
    };
</script>
